// Read ellipsometer values via LabJack
//use easyU3 code from labjack as basis

// use channel 0 as input for photodiode.
// use channel 4 as control flag input
// use channel 5 as position flag input

// manually select analyser angle

// version 1.2 add ncurses functionality

#include "ManEllips.h"
#include "fresnel.h"
#include "film.h"


int manE(WINDOW *mainwnd, ellipspar_t *ellipsparams)
{
	clear();
    HANDLE hDevice;
    u3CalibrationInfo caliInfo;
    int localID;
    long Reference,Count, error;
    int MainLoop,values;
    int LoopCheck;
    double Voltage[72],value;
    long DAC1Enable;
    
    // variables for Psi, Delta calculation
    double k0,k1,k2;
    double angle;
    char texta[64];// user input angle
    double psi,delta;	
	 
    
    //Open first found U3 over USB
    localID = -1;
    if( (hDevice = openUSBConnection(localID)) == NULL)
        goto done;
	printw("found U3\n");
	refresh();
    //Get calibration information from UE9
    if(getCalibrationInfo(hDevice, &caliInfo) < 0)
        goto close;
	printw("got calib info\n");
	refresh();
	
// initialise ncurses
LoopCheck=1;// keeps track of whether a channel has been set to the correct type
Reference=1;
Count=1;
//Voltage=0.;//default value
DAC1Enable=1;
int j;
{	
	scrollok(mainwnd,TRUE);
for (j=0;j<72;j++)
{
	wprintw(mainwnd,"Set analyzer to %1.1f degrees and press Return key",5.*j);
		
	refresh();
	getch();
 	
 	// Now get photodiode value	
 	if ((error=eAIN( hDevice,&caliInfo,LoopCheck,&DAC1Enable,0,31,&value,0,0,0,0,0,0))!=0) goto close;
	   // function call has worked so set LoopCheck to zero for future calls
	LoopCheck=0;
	Voltage[j]=value;
	wprintw(mainwnd," %1.1f\n",value);
	
	refresh();
 }
	clear();
	
	VoltageToPsiDelta(Voltage,72,  &psi, &delta,mainwnd);
 // Now have the data, need to convert to Psi and Delta
/*
 angle=70; // default value
 k0=0.;
 k1=0.;
 k2=0.;
 
// k0= is the average value of the readings.
 int i;
 for (i=0;i<36;i++) k0+=Voltage[i];
 k0/=36.;
 
 wprintw(mainwnd,"k0=%.4f\n",k0);
	refresh();
double rangle;

rangle=5.0*M_PI/180.; 
// k1 =2*sum(Vi*cos(2*anglei))/N
// k1 =2*sum(Vi*sin(2*anglei))/N

for (i=0;i<36;i++) k1+=(Voltage[i]*cos(2.0*rangle*i));
for (i=0;i<36;i++) k2+=(Voltage[i]*sin(2.0*rangle*i)); 

k1*=(2.0/36.);
k2*=(2.0/36.0);

wprintw(mainwnd,"k0=%2.3f k1=%2.3f k2=%2.3f \n",k0,k1,k2);
	refresh();
psi=atan(sqrt((k0+k1)/(k0-k1)));
delta=acos(k2/sqrt((k0*k0-k1*k1)));
*/
//dump data


wprintw(mainwnd,"Psi=%1.3f  Delta=%1.3f\n",180.*psi/M_PI,180.*delta/M_PI);
	refresh();
//scanf("%s",texta);

MainLoop++;
}
	echo();
	
	
	
	error = 0;
	error = solvepsidelta(mainwnd,ellipsparams,psi,delta); // call routine to solve for 


	
close:
    if(error > 0)
        wprintw(mainwnd,"Received an error code of %ld\n", error);
	refresh();
    closeUSBConnection(hDevice);
done:
    return 0;
}

